package com.jd.cart.controller;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.jd.cart.model.CartItem;
import com.jd.cart.utils.CookieUtils;

/**
 * java.lang.IllegalArgumentException: An invalid character [34] was present in the Cookie value
 * @author WHSXT-LTD
 *
 */
@RestController
public class CartController {
	/**
	 * 添加到购物车里面
	 * skuId:商品的skuId
	 * count：该条目的数量
	 * 在没有登录时，添加到Cookie 里面
	 * @return
	 */
	@GetMapping("/addCart")
	public ResponseEntity<Void> addCart(HttpServletRequest request ,HttpServletResponse response ,Long skuId ,@RequestParam (defaultValue = "1")Integer count){
		Map<Long,CartItem> carts = null ;
		//1 之前在cookie 里面没有值，直接往里面添加
		if((carts = getCartFromCookie(request))==null) { //2 添加之前Cookie有值，获取之前的值
			carts = new HashMap<Long, CartItem>();
		}
		// 添加到购物车时也有2 种情况
		// 1 之前购物车里面有该条目 ，只需要改变数量
		// 2 之前购物车里面没有该条目，新增一个新的值，并且设置新的数量
		if(carts.containsKey(skuId)) {
			CartItem cartItem = carts.get(skuId);
			cartItem.setCount(cartItem.getCount()  + count);
		}else {
			CartItem cartItem = new CartItem();
			cartItem.setSkuId(skuId);
			cartItem.setCount(count);
			carts.put(skuId, cartItem) ;
		}
		
		// 保存该购物车，把map 集合再次放在Cookie 里面
		saveCartItem(carts,request,response);

		return ResponseEntity.ok().build();
	}

	@GetMapping("/cart/getTotal")
	public ResponseEntity<Integer> getTotalCart(HttpServletRequest request){
		Map<Long, CartItem> carts = getCartFromCookie(request);
		if(carts==null) {
			return ResponseEntity.ok(0) ;
		}
		Set<Long> skuIds = carts.keySet();
		int total = 0 ;
		for (Long sku : skuIds) {
			CartItem cartItem = carts.get(sku);
			Integer count = cartItem.getCount();
			total += count ;
		}
		return ResponseEntity.ok(total) ;
	}
	/**
	 * 保存到购物车里面
	 * java.lang.IllegalArgumentException: An invalid character [34] was present in the Cookie value
	 * @param carts
	 * @param request
	 * @param response
	 */
	private void saveCartItem(Map<Long, CartItem> carts, HttpServletRequest request, HttpServletResponse response) {
		CookieUtils.setCookie(request, response, "jd-cart", JSON.toJSONString(carts), 30*24*7200,true);
	}

	private Map<Long, CartItem> getCartFromCookie(HttpServletRequest request) {
		String cartJson = CookieUtils.getCookieValue(request, "jd-cart",true);
		if(StringUtils.hasText(cartJson)) {
			// 在json 序列化丢失了泛型的信息
			// 使用类型应用保证泛型里面的数据 TypeReference ,强行得到泛型的数据
			Type type = new TypeReference<Map<Long,CartItem>>() {}.getType();
			Map<Long,CartItem> cart = JSON.parseObject(cartJson,type);
			return cart ;
		}
		return null;
	}
}
